package cn.tedu.thread;

import java.awt.*;

public class DeadLockDemo {
    public static Object chopsticks = new Object();
    public static Object spoon = new Object();

    public static void main(String[] args) {
        Thread np = new Thread(){
            @Override
            public void run() {
                System.out.println("北方人开始吃饭");
                System.out.println("北方人去拿筷子");
                synchronized (chopsticks){
                    System.out.println("北方人拿起筷子开始吃饭");
                    try {
                        Thread.sleep(5000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println("北方人吃完了饭，去拿勺...");
                    synchronized (spoon){
                        System.out.println("北方人拿起了勺子开始喝汤");
                        try {
                            Thread.sleep(5000);
                            System.out.println("北方人喝完了汤");
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        System.out.println("北方人放下了勺子");
                    }
                    System.out.println("北方人放下了筷子,吃饭完毕");
                }
            }
        };
        Thread sp = new Thread(){
            public void run(){
                System.out.println("南方人开始吃饭.");
                System.out.println("南方人去拿勺...");
                synchronized (spoon){
                    System.out.println("南方人拿起了勺开始喝汤...");
                    try {
                        Thread.sleep(5000);
                    } catch (InterruptedException e) {
                    }
                    System.out.println("南方人喝完了汤，去拿筷子...");

                synchronized (chopsticks){
                    System.out.println("南方人拿起了筷子开始吃饭...");
                    try {
                        Thread.sleep(5000);
                    }catch (InterruptedException e){

                    }
                    System.out.println("南方人吃完饭");
                }
                System.out.println("南方人放下了筷子");
            }
                System.out.println("南方人放下了勺，吃饭完毕!");
        }
        };
        np.start();
        sp.start();
    }
}
